# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os

from conan import ConanFile
from conan.tools.scm import Git
from conan.tools.files import copy
from conan.tools.cmake import CMake, CMakeToolchain, cmake_layout, CMakeDeps

required_conan_version = ">=2.13.0"


class Re2Conan(ConanFile):
    name = "re2"
    license = "BSD-3-Clause"
    description = "RE2 is a fast, safe, thread-friendly regular expression library"
    settings = "os", "arch", "compiler", "build_type"
    topics = ("regular expressions", "regex", "performance", "c++")
    _cmake = None
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
    }
    default_options = {
        "shared": False,
        "fPIC": True,
    }

    def layout(self):
        cmake_layout(self)

    def source(self):
        source = self.conan_data["sources"][self.version]
        git = Git(self)
        git.fetch_commit(url=source["url"], commit=source["branch"])

    def generate(self):
        tc = CMakeToolchain(self)
        tc.variables["RE2_BUILD_TESTING"] = "OFF"
        tc.variables["BUILD_SHARED_LIBS"] = not self.options.shared
        tc.variables["CMAKE_POSITION_INDEPENDENT_CODE"] = self.options.fPIC
        
        # 添加编译标志
        tc.extra_cflags = ["-D_FORTIFY_SOURCE=2"]
        tc.extra_cxxflags = ["-D_FORTIFY_SOURCE=2"]

        tc.generate()

    def build(self):
        cmake = self._configure_cmake()
        cmake.build()

    def package(self):
        cmake = self._configure_cmake()
        cmake.install()
        copy(self, "permissions.ini", src=self.source_folder, dst=self.package_folder)

    def package_info(self):
        self.cpp_info.libs = ["re2"]
        self.env_info.libdirs = ["lib"]
        self.env_info.includedirs = ["include"]

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        self._cmake.configure(cli_args=["--no-warn-unused-cli"])
        return self._cmake